package com.qx.grainmall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.qx.common.utils.CartConstant;
import com.qx.common.utils.R;
import com.qx.grainmall.cart.feign.SkuInfoFeignService;
import com.qx.grainmall.cart.interceptor.CartInterceptor;
import com.qx.grainmall.cart.service.CartService;
import com.qx.grainmall.cart.to.UserInfoTo;
import com.qx.grainmall.cart.vo.CartItemVo;
import com.qx.grainmall.cart.vo.CartVo;
import com.qx.grainmall.cart.vo.SkuInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SkuInfoFeignService skuInfoFeignService;



    //添加商品到购物车
    @Override
    public CartItemVo addToCart(Long skuId, Integer num) {
    //获取该用户操作redis的hash结构的ops
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        //redis中有无该商品
        String o = (String) cartOps.get(skuId.toString());
        //有商品 就修改数量
        if(o != null){
            CartItemVo cartItemVo = JSON.parseObject(o, new TypeReference<CartItemVo>() {
            });
            cartItemVo.setCount(cartItemVo.getCount()+num);
            cartOps.put(skuId.toString(),JSON.toJSONString(cartItemVo));
            return cartItemVo;
        }else {
            //没有该商品 的时候再去添加
            CartItemVo cartItemVo = new CartItemVo();
            //远程调用 商品信息
                //1,sku 的基本信息
            R info = skuInfoFeignService.info(skuId);
            SkuInfoVo skuInfoVo = info.getData(new TypeReference<SkuInfoVo>() {
            });
            cartItemVo.setSkuId(skuInfoVo.getSkuId());
            cartItemVo.setSkuTitle(skuInfoVo.getSkuTitle());
            cartItemVo.setSkuImg(skuInfoVo.getSkuDefaultImg());
            cartItemVo.setPrice(skuInfoVo.getPrice());
            cartItemVo.setCount(num); //数量
            //2 商品销售属性信息
            List<String> stringlist = skuInfoFeignService.stringlist(skuId);
            cartItemVo.setSkuAttrValues(stringlist);
            cartOps.put(skuId.toString(),JSON.toJSONString(cartItemVo));
            return cartItemVo;
        }

    }

    @Override
    public CartItemVo getCart(Long skuId) {
        //获取当前用户
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String o = (String) cartOps.get(skuId.toString());
        if(o != null) {
            CartItemVo cartItemVo = JSON.parseObject(o, new TypeReference<CartItemVo>() {
            });
            return cartItemVo;
        }
        return null;
    }

    @Override
    public CartVo getAllCartVo() {
        //获取用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //临时购物车ops
        String empkey = CartConstant.CART_PRE+userInfoTo.getUserKey();
        BoundHashOperations<String, Object, Object> empops = stringRedisTemplate.boundHashOps(empkey);
        // gulimall:cart:10 用户购物车ops
        String userCartkey = CartConstant.CART_PRE+userInfoTo.getUserId();
        BoundHashOperations<String, Object, Object> userops = stringRedisTemplate.boundHashOps(userCartkey);

        //有用户登录
        if(userInfoTo.getUserId() != null){
            //获取临时购物车所有数据
            List<CartItemVo> collect = empops.values().stream().map(e -> {
                String s = (String) e;
                CartItemVo cartItemVo = JSON.parseObject(s, new TypeReference<CartItemVo>() {
                });
                return cartItemVo;
            }).collect(Collectors.toList());

            //向用户购物车添加
            //每一个临时购物车中的数据
            for (CartItemVo cartItemVo : collect) {
                //添加到购物车
                addToCart(cartItemVo.getSkuId(),cartItemVo.getCount());
            }

            //删除临时购物车数据
            stringRedisTemplate.delete(empkey);
            //查询用户购物车
            List<CartItemVo> list2 = userops.values().stream().map(e -> {
                String s = (String) e;
                CartItemVo cartItemVo = JSON.parseObject(s, new TypeReference<CartItemVo>() {
                });
                return cartItemVo;
            }).collect(Collectors.toList());
            //封装购物车数据
            CartVo cartVo = new CartVo();
            cartVo.setItems(list2);
            return cartVo;
        }else{
            //没有用户购物车 操作临时购物车
            //获取临时购物车所有数据
            List<CartItemVo> collect = empops.values().stream().map(e -> {
                String s = (String) e;
                CartItemVo cartItemVo = JSON.parseObject(s, new TypeReference<CartItemVo>() {
                });
                return cartItemVo;
            }).collect(Collectors.toList());
            //封装购物车数据
            CartVo cartVo = new CartVo();
            cartVo.setItems(collect);
            return cartVo;
        }
    }

    //改变选中状态
    @Override
    public void changeCheck(Long skuId, Boolean check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String o = (String) cartOps.get(skuId.toString());
        //转为itemvo对象
        CartItemVo cartItemVo = JSON.parseObject(o, new TypeReference<CartItemVo>() {
        });
        cartItemVo.setCheck(check);
        //保存回去
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItemVo));
    }

    //更改商品数量
    @Override
    public void updCount(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String o = (String) cartOps.get(skuId.toString());
        //转为itemvo对象
        CartItemVo cartItemVo = JSON.parseObject(o, new TypeReference<CartItemVo>() {
        });
        cartItemVo.setCount(num);
        //保存回去
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItemVo));
    }
    //删除某一项商品
    @Override
    public void del(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }


    //获取该用户操作redis的hash结构的ops(操作对象)
    private BoundHashOperations<String, Object, Object> getCartOps() {
        //获取用户id
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String key = "";
        if(userInfoTo.getUserId() != null){//登录后的用户
            String userId = userInfoTo.getUserId();
            key = CartConstant.CART_PRE+userId;
        }else{ //临时用户
            String userKey = userInfoTo.getUserKey();
            key = CartConstant.CART_PRE+userKey;
        }
        BoundHashOperations<String, Object, Object> cartops = stringRedisTemplate.boundHashOps(key);
        return cartops;
    }

}
